require_relative '../test_helper'

module Resources
  class UsersTest < Resources::Test
    def setup
      super # 重要
      @user = users(:one)
    end

    def test_get_all
      get path('users')
      assert last_response.ok?
      assert_equal({
        users: [
          { id: 1, name: 'xiaohong', age: 18 },
          { id: 2, name: 'xiaoming', age: 20 }
        ]
      }.as_json, JSON.parse(last_response.body))
    end

    def test_create_new
      post path('users'),
           { user: attributes_for(:user, name: 'xiaohuang') }.to_json,
           { 'CONTENT_TYPE' => 'application/json' }
      assert last_response.created?
      assert_equal({
        user: {
          id: 3, name: 'xiaohuang', age: 18
        }
      }.as_json, JSON.parse(last_response.body))
    end

    def test_show_my_own
      header 'X-Token', @user.to_token
      get path('user')
      assert last_response.ok?
      assert_equal({
        user: {
          id: 1, name: 'xiaohong', age: 18
        }
      }.as_json, JSON.parse(last_response.body))
    end

    def test_update_my_own
      header 'X-Token', @user.to_token
      put path('user'), { user: { name: 'xiaohuang', age: 20 } }.to_json, { 'CONTENT_TYPE' => 'application/json' }
      assert last_response.ok?
      assert_equal({
        user: {
          id: 1, name: 'xiaohuang', age: 20
        }
      }.as_json, JSON.parse(last_response.body))
    end
  end
end
